# _*_ coding : utf-8 _*_
# @Time : 2023/12/5 20:36
# @Author : 韩宗森
# @File : 11_post请求肯德基
# @Project : pythonProject

"""
post 请求
https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname

cname: 北京
pid:
pageIndex: 2
pageSize: 10

"""

import urllib.parse
import urllib.request


def create_request(page):
    base_url = 'https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'

    data = {
        'cname': '北京',
        'pid': '',
        'pageIndex': 2,
        'pageSize': 10
    }

    data = urllib.parse.urlencode(data).encode('utf-8')

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'
    }

    # (1)请求对象的定制
    request = urllib.request.Request(url=base_url, headers=headers, data=data)

    return request


# (2)获取响应的数据
def get_content(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content


# (3)数据下载到本地
def down_load(page, content):
    with open('肯德基_' + str(page) + '.json', 'w', encoding='utf-8') as fp:
        fp.write(content)


if __name__ == '__main__':
    start_page = 1
    end_page = 10
    for page in range(start_page, end_page + 1):
        # 请求对象的定制
        request = create_request(page)
        # 获取网页源码
        content = get_content(request)
        # (3)数据下载到本地
        down_load(page, content)
